window.onload = function (){
    showShopInfo();
}

/**
 * 显示购物车信息
 */
function showShopInfo(){
    axios.get("/shop/showShopList").then(resp =>{
        let shopList = resp.data;
        let str = "";
        let total = 0;
        shopList.forEach(n =>{
           str += `<tr><td>${n.product.name}</td><td>${n.product.price}</td><td>${n.product.address}</td>
            <td><input type="text" value="${n.num}" onblur="updateNum(${n.id},this)"></td><td>${n.num * n.product.price}</td>
            <td><input type="button" value="移除商品" onclick="del(${n.id})"></td></tr>`;
           total += n.product.price * n.num;
        });
        $("data").innerHTML = str;
        $("totalPriceSpan").innerHTML = total;
    })
}

/**
 * 移除购物车商品
 * @param shopId 购物车ID
 */
function del(shopId){
    axios.get("/shop/del",{
        params:{shopId}
    }).then(resp =>{
        if(resp.data == "ok"){
            showShopInfo();
        }
    })
}

/**
 * 修改数量
 * @param shopId 购物车ID
 * @param txtObj 数量文本框
 */
function updateNum(shopId,txtObj){
    var num = parseInt(txtObj.value);
    if(isNaN(num)){
        num = 1;
    }
    txtObj.value = num;

    axios.get("/shop/updateNum",{
        params: {
            shopId,
            num
        }
    }).then(resp =>{
       if(resp.data == "ok"){
           showShopInfo();
       }
    });
}